package com.jy.datapipeline.export.dao.impl;

import com.jy.datapipeline.common.constants.ExpConstants;
import com.jy.datapipeline.common.util.AssertUtil;
import com.jy.datapipeline.export.dao.ExpTaskExecuteDetailLogDao;
import com.jy.datapipeline.export.entity.ExpTaskExecuteDetailLogModel;
import com.jy.datapipeline.common.util.DateUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Slf4j
@Repository
public class ExpTaskExecuteDetailLogDaoImpl implements ExpTaskExecuteDetailLogDao {
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public List<Map<String, Object>> findExpTaskExecuteDetailByList(String taskId,
        String taskExecuteLogId,String ruleTbl,String expStatus, int iDisplayStart, int iDisplayLength) {
        List<Map<String, Object>> list=new ArrayList<>();
        try {
            StringBuffer sb=new StringBuffer();
            Map<String,Object> params = new HashMap<String,Object>();
            sb.append("SELECT a.id,a.rule_id,a.task_id,a.task_executelog_id,a.data_source_id,"
                + " a.rule_tbl,a.rule_type,a.exp_status,a.data_file_path,a.store_type,a.data_file_count,"
                + " DATE_FORMAT(a.export_start_time,'%Y-%m-%d %H:%i:%s') as export_start_time, "
                + " DATE_FORMAT(a.export_end_time,'%Y-%m-%d %H:%i:%s') as export_end_time, "
                + " DATE_FORMAT(a.sftp_start_time,'%Y-%m-%d %H:%i:%s') as sftp_start_time, "
                + " DATE_FORMAT(a.sftp_end_time,'%Y-%m-%d %H:%i:%s') as sftp_end_time, "
                + " DATE_FORMAT(a.feedback_time,'%Y-%m-%d %H:%i:%s') as feedback_time, "
                + " DATE_FORMAT(a.delete_time,'%Y-%m-%d %H:%i:%s') as delete_time, "
                + " DATE_FORMAT(a.update_time,'%Y-%m-%d %H:%i:%s') as update_time,a.error_msg from exp_task_execute_detail_log a   "
                + " where 1=1  ");
            if(taskId!=null && !taskId.equals("")){
                sb.append(" and a.task_id =:taskId");
                params.put("taskId",taskId);
            }
            if(expStatus!=null && !expStatus.equals("")){
                sb.append(" and a.exp_status =:expStatus");
                params.put("expStatus",Integer.parseInt(expStatus));
            }
            if(ruleTbl!=null && !ruleTbl.equals("")){
                sb.append(" and a.rule_tbl like:ruleTbl");
                params.put("ruleTbl","%"+ruleTbl+"%");
            }
            if(taskExecuteLogId!=null && !taskExecuteLogId.equals("")){
                sb.append(" and a.task_executelog_id =:taskExecuteLogId");
                params.put("taskExecuteLogId",taskExecuteLogId);
            }
            sb.append(" order by a.update_time desc  ");
            if(iDisplayStart>-1 && iDisplayLength>-1){
                sb.append("LIMIT  :iDisplayStart ,:iDisplayLength ;");
                params.put("iDisplayStart",iDisplayStart);
                params.put("iDisplayLength",iDisplayLength);
            }
            list=this.namedParameterJdbcTemplate.queryForList(sb.toString(),params);
        }catch (Exception e){
            log.error("findExpTaskExecuteLogByList exception",e);
        }

        return list;
    }



    @Override
    public boolean deleteByTaskId(String taskId) {
        Map<String,Object> params=new HashMap<>();
        String sql="delete from exp_task_execute_detail_log where task_id=:taskId";
        params.put("taskId",taskId);
        int req=this.namedParameterJdbcTemplate.update(sql,params);
        return req>0?true:false;
    }

    @Override
    public boolean deleteByTaskExecuteLogId(String taskExecuteLogId) {
        Map<String,Object> params=new HashMap<>();
        String sql="delete from exp_task_execute_detail_log where task_executelog_id=:taskExecuteLogId";
        params.put("taskExecuteLogId",taskExecuteLogId);
        int req=this.namedParameterJdbcTemplate.update(sql,params);
        return req>0?true:false;
    }

    @Override
    public boolean updateExpStatus(ExpTaskExecuteDetailLogModel etedl) {
        Map<String,Object> params=new HashMap<>();

        StringBuilder sb=new StringBuilder();
        sb.append("update exp_task_execute_detail_log set exp_status=:expStatus,update_time=NOW() ");
        params.put("expStatus",etedl.getExpStatus());
        if(etedl.getDataFileCount()>0){
            sb.append(" , data_file_count=:dataFileCount");
            params.put("dataFileCount",etedl.getDataFileCount());
        }
        if(etedl.getExportStartTime()!=null){
            sb.append(" , export_start_time=:exportStartTime");
            params.put("exportStartTime", DateUtils.formatDate(etedl.getExportStartTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(etedl.getExportEndTime()!=null){
            sb.append(" , export_end_time=:exportEndTime");
            params.put("exportEndTime",DateUtils.formatDate(etedl.getExportEndTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(etedl.getSftpStartTime()!=null){
            sb.append(" , sftp_start_time=:sftp_start_time");
            params.put("sftp_start_time",DateUtils.formatDate(etedl.getSftpStartTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(etedl.getSftpeEndtime()!=null){
            sb.append(" , sftp_end_time=:sftp_end_time");
            params.put("sftp_end_time",DateUtils.formatDate(etedl.getSftpeEndtime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(etedl.getFeedbackTime()!=null){
            sb.append(" , feedback_time=:feedback_time");
            params.put("feedback_time",DateUtils.formatDate(etedl.getFeedbackTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(etedl.getDeleteTime()!=null){
            sb.append(" , delete_time=:delete_time");
            params.put("delete_time",DateUtils.formatDate(etedl.getDeleteTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(etedl.getDataFilePath()!=null){
            sb.append(" , data_file_path=:data_file_path");
            params.put("data_file_path",etedl.getDataFilePath());
        }
        if(etedl.getDataFileNamePrefix()!=null){
            sb.append(" , data_file_name_prefix=:data_file_name_prefix");
            params.put("data_file_name_prefix",etedl.getDataFileNamePrefix());
        }
        if(etedl.getDataFileCount()>0){
            sb.append(" , data_file_count=:data_file_count");
            params.put("data_file_count",etedl.getDataFileCount());
        }
        if(etedl.getErrorMsg()!=null && !etedl.getErrorMsg().equals("")){
            sb.append(" , error_msg=:errorMsg");
            params.put("errorMsg",etedl.getErrorMsg());
        }
        if(etedl.getDataFileInfo()!=null && !etedl.getDataFileInfo().equals("")){
            sb.append(" ,data_file_info=:dataFileInfo");
            params.put("dataFileInfo",etedl.getDataFileInfo());
        }
        sb.append("  where task_execute_detail_id=:task_execute_detail_id");
        params.put("task_execute_detail_id",etedl.getTaskExecuteDetailId());
        int req=this.namedParameterJdbcTemplate.update(sb.toString(),params);
        return req>0?true:false ;
    }

    @Override
    public List<Map<String, Object>> findBytaskExecutelogLogId(String taskExecuteLogId) {
        List<Map<String, Object>> list=new ArrayList<>();
        try {
            StringBuffer sb=new StringBuffer();
            Map<String,Object> params = new HashMap<String,Object>();
            sb.append("SELECT a.id,a.rule_id,a.task_id,a.task_executelog_id,a.data_source_id,"
                + " a.rule_tbl,a.rule_type,a.exp_status,a.data_file_path,a.store_type,a.data_file_count,"
                + " DATE_FORMAT(a.export_start_time,'%Y-%m-%d %H:%i:%s') as export_start_time, "
                + " DATE_FORMAT(a.export_end_time,'%Y-%m-%d %H:%i:%s') as export_end_time, "
                + " DATE_FORMAT(a.sftp_start_time,'%Y-%m-%d %H:%i:%s') as sftp_start_time, "
                + " DATE_FORMAT(a.sftp_end_time,'%Y-%m-%d %H:%i:%s') as sftp_end_time, "
                + " DATE_FORMAT(a.feedback_time,'%Y-%m-%d %H:%i:%s') as feedback_time, "
                + " DATE_FORMAT(a.delete_time,'%Y-%m-%d %H:%i:%s') as delete_time, "
                + " DATE_FORMAT(a.update_time,'%Y-%m-%d %H:%i:%s') as update_time,a.error_msg from exp_task_execute_detail_log a   "
                + " where 1=1  ");

            if(taskExecuteLogId!=null && !taskExecuteLogId.equals("")){
                sb.append(" and a.task_executelog_id =:taskExecuteLogId");
                params.put("taskExecuteLogId",taskExecuteLogId);
            }
            sb.append(" order by a.update_time desc  limit 0,1 ");

            list=this.namedParameterJdbcTemplate.queryForList(sb.toString(),params);
        }catch (Exception e){
            log.error("findExpTaskExecuteLogByList exception",e);
        }

        return list;
    }

    @Override
    public int findExpTaskExecuteDetailByCount(String taskId, String taskExecuteLogId,String ruleTbl,
        String expStatus) {
        int count=0;
        List<Map<String, Object>> list=new ArrayList<>();
        try {
            StringBuffer sb=new StringBuffer();
            Map<String,Object> params = new HashMap<String,Object>();
            sb.append("SELECT COUNT(a.id) as count from exp_task_execute_detail_log a   "
                + " where 1=1  ");
            if(taskId!=null && !taskId.equals("")){
                sb.append(" and a.task_id =:taskId");
                params.put("taskId",taskId);
            }
            if(expStatus!=null && !expStatus.equals("")){
                sb.append(" and a.exp_status =:expStatus");
                params.put("expStatus",Integer.parseInt(expStatus));
            }
            if(ruleTbl!=null && !ruleTbl.equals("")){
                sb.append(" and a.rule_tbl like:ruleTbl");
                params.put("ruleTbl","%"+ruleTbl+"%");
            }
            if(taskExecuteLogId!=null && !taskExecuteLogId.equals("")){
                sb.append(" and a.task_executelog_id =:taskExecuteLogId");
                params.put("taskExecuteLogId",taskExecuteLogId);
            }
            sb.append(" order by a.update_time desc  ");

            list=this.namedParameterJdbcTemplate.queryForList(sb.toString(),params);
            if(list.size()>0){
                count=Integer.parseInt(list.get(0).get("count")!=null?list.get(0).get("count").toString():"0");
            }
        }catch (Exception e){
            log.error("findExpTaskExecuteLogByList exception",e);
        }

        return count;
    }

    @Override
    public String findExpTaskExeDetailLatestExpStatusByTaskId(String task_id) {
        Map<String,Object> params = new HashMap<>();
        params.put("taskId", task_id);
        String sql = "select exp_status from exp_task_execute_detail_log where task_id = :taskId order by update_time desc limit 1";
        List<Map<String, Object>> list = namedParameterJdbcTemplate.queryForList(sql, params);
        if (!list.isEmpty()) {
            return String.valueOf(list.get(0).get("exp_status"));
        }
        return null;
    }

    @Override
    public String findExecuteLogIdByExeDetailId(String taskExecuteDetailId) {
        Map<String,Object> params=new HashMap<>();
        params.put("taskExecuteDetailId",taskExecuteDetailId);
        String sql="select task_executelog_id from exp_task_execute_detail_log where task_execute_detail_id=:taskExecuteDetailId";
        List<Map<String, Object>> list = this.namedParameterJdbcTemplate.queryForList(sql, params);
        AssertUtil.isNull(list, ExpConstants.QUERY_FAIL);
        return (String) list.get(0).get("task_executelog_id");
    }
}
